{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "agmT3hrjsffX"
      },
      "source": [
        "# Gemini API: JSON Mode Quickstart with REST\n",
        "\n",
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/rest/JSON_mode_REST.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JMNKdTpTGZET"
      },
      "source": [
        "The Gemini API can be used to generate a JSON output if you set the schema that you would like to use. This notebook provides a code example that shows you how to get started with JSON mode using `curl`.\n",
        "\n",
        "You can run this in Google Colab, or you can copy/paste the `curl` commands into your terminal.\n",
        "\n",
        "### Authentication\n",
        "\n",
        "To run this notebook, your API key must be stored it in a Colab Secret named GOOGLE_API_KEY. If you are running in a different environment, you can store your key in an environment variable. See [Authentication](../../quickstarts/Authentication.ipynb) to learn more."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "R-Vw_mOM_WD0"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from google.colab import userdata"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wCkLTpb3oTXE"
      },
      "outputs": [],
      "source": [
        "os.environ['GOOGLE_API_KEY'] = userdata.get('GOOGLE_API_KEY')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tjGqGBZ9yARd"
      },
      "source": [
        "## Activate JSON Mode\n",
        "\n",
        "To activate JSON mode, set `response_mime_type` to `application/json` in the `generationConfig`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "be337c539615"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.5-flash\" # @param [\"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-pro\",\"gemini-3-pro-preview\"] {\"allow-input\":true, isTemplate: true}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eA7I_Ww8IETn"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"candidates\": [\n",
            "    {\n",
            "      \"content\": {\n",
            "        \"parts\": [\n",
            "          {\n",
            "            \"text\": \"[{\\\"recipe_name\\\":\\\"Chocolate Chip Cookies\\\"},{\\\"recipe_name\\\":\\\"Peanut Butter Cookies\\\"},{\\\"recipe_name\\\":\\\"Oatmeal Raisin Cookies\\\"},{\\\"recipe_name\\\":\\\"Sugar Cookies\\\"},{\\\"recipe_name\\\":\\\"Shortbread Cookies\\\"}] \\n\"\n",
            "          }\n",
            "        ],\n",
            "        \"role\": \"model\"\n"
          ]
        }
      ],
      "source": [
        "%%bash\n",
        "\n",
        "curl \"https://generativelanguage.googleapis.com/v1beta/models/${MODEL_ID}:generateContent?key=$GOOGLE_API_KEY\" \\\n",
        "-H 'Content-Type: application/json' \\\n",
        "-d '{\n",
        "    \"contents\": [{\n",
        "      \"parts\":[\n",
        "        {\"text\": \"List a few popular cookie recipes using this JSON schema:\n",
        "          {'type': 'object', 'properties': { 'recipe_name': {'type': 'string'}}}\"\n",
        "          }\n",
        "        ]\n",
        "    }],\n",
        "    \"generationConfig\": {\n",
        "        \"response_mime_type\": \"application/json\",\n",
        "    }\n",
        "}' 2> /dev/null | head"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OxN68aKNDxEV"
      },
      "source": [
        "To turn off JSON mode, set `response_mime_type` to `text/plain` (or omit the `response_mime_type` parameter)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jXkRYBhbB_b2"
      },
      "source": [
        "## Next Steps\n",
        "### Useful API references:\n",
        "\n",
        "Check the [structured ouput](https://ai.google.dev/gemini-api/docs/structured-output) documentation or the [`GenerationConfig`](https://ai.google.dev/api/generate-content#generationconfig) API reference for more details \n",
        "\n",
        "### Related examples\n",
        "\n",
        "* The constrained output is used in the [Text summarization](../../examples/json_capabilities/Text_Summarization.ipynb) example to provide the model a format to summarize a story (genre, characters, etc...)\n",
        "* The [Object detection](../../examples/Object_detection.ipynb) examples are using the JSON constrained output to normalize the output of the detection.\n",
        "\n",
        "### Continue your discovery of the Gemini API\n",
        "\n",
        "JSON is not the only way to constrain the output of the model, you can also use an [Enum](../../quickstarts/Enum.ipynb). [Function calling](../../quickstarts/Function_calling.ipynb) and [Code execution](../../quickstarts/Code_Execution.ipynb) are other ways to enhance your model by using your own functions or by letting the model write and run them."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "JSON_mode_REST.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
